import datetime,jwt,json
from django.http import JsonResponse
from django.views import View
from .models import User, Roles, Menu
from django.conf import settings
from .serializer import *
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action
# Create your views here.

# 登录视图


def login(request):
    params = json.loads(request.body)
    user = User.objects.get(username=params.get(
        'username'), password=params.get('password'))
    result = {}
    if user is not None:
        # 构造header
        headers = {
            'typ': 'jwt',
            'alg': 'HS256'
        }
        # 构造payload
        payload = {
            'username': user.username,  # 自定义用户名
            'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=5)  # 超时时间
        }
        data = {}
        token = jwt.encode(payload=payload, key=settings.SECRET_KEY,
                           algorithm="HS256", headers=headers)
        result['massage'] = '登陆成功啦'
        result['status'] = 0
        result['data'] = {}
        result['data']['accessToken'] = token
        result['data']['username'] = user.username
    else:
        result['massage'] = '登陆失败'
        result['status'] = 'error'
    return JsonResponse(result)

# 获取用户信息


class UserInfo(View):
    def post(self, request):
        userinfo = json.loads(request.body)
        try:
            user = User.objects.get(username=userinfo['username'])
            role = user.rid.values()
            return JsonResponse({
                'status': 0,
                'message': '成功',
                'data': {
                    'roleName': role[0]['roleName']
                }
            })
        except:
            return JsonResponse({
                'status': 400,
                'message': '获取数据失败',
            })

# 根据角色查询授权菜单


def routes(request):
    b = json.loads(request.body)
    role = Roles.objects.filter(roleName=b['roleName']).first()
    menuobj = list(role.menu.all().values())
    print(menuobj)
    accessRoutes = []
    for i in menuobj:
        accessRoutes.append(i['path'])
    return JsonResponse({
        'status': 0,
        'message': '获取成功',
        'data': {
            "accessRoutes": accessRoutes,
        }
    })

# 根据橘色名称查询授权菜单


class MenuView(ModelViewSet):
    queryset = Menu.objects.all()
    serializer_class = MenuSerializer

    @action(methods=['put'], detail=True)
    def edit(self, request, pk):
        return self.update(request, pk, partial=True)


class RoleView(ModelViewSet):
    queryset = Roles.objects.all()
    serializer_class = RoleSerializer

    @action(methods=['put'], detail=True)
    def edit(self, request, pk):
        return self.update(request, pk, partial=True)


class UserView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

    @action(methods=['put'], detail=True)
    def edit(self, request, pk):
        return self.update(request, pk, partial=True)
